package com.fanrui.code.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.ibatis.session.SqlSession;

import com.fanrui.code.db.jvmdb.JvmDao;
import com.fanrui.code.entity.PlayerLog;
import com.fanrui.code.entity.PlayerLogMapper;
import com.fanrui.code.thread.MainLoopPlus.StrongRunnable;
import com.fanrui.code.util.SessionUtil;
import com.fanrui.code.util.core.LoopThreadPool;
import com.fanrui.code.util.logger.Stdout;

public class PlayerLogDao extends JvmDao<PlayerLog, Integer> {

	// singleton
	private PlayerLogDao() {
		super(PlayerLog.class);
	}

	private static class PlayerLogDaoSingleton {
		private static PlayerLogDao instance = new PlayerLogDao();
	}
	
	public static PlayerLogDao getInstance() {
		return PlayerLogDaoSingleton.instance;
	}
	
	public void startSave(){
		LoopThreadPool.getInstance().scheduleAtFixedRate(new StrongRunnable() {

			@Override
			protected void strongRun() throws Exception {
				updateToDB();
			}

		}, 5, 5, TimeUnit.SECONDS);
	}

	protected void updateToDB() {
		if (modifiedEntities != null && !modifiedEntities.isEmpty()) {
			synchronized(modifiedEntities) {
				Stdout.GET().info("PlayerLog:定时更新数据到数据库!此次更新{}条数据",modifiedEntities.size());
				SqlSession session = SessionUtil.getSession();
				PlayerLogMapper mapper = session.getMapper(PlayerLogMapper.class);
				List<PlayerLog> logList = new ArrayList<>(modifiedEntities.keySet());
				mapper.insertBatchSelective(logList);
				session.commit();
				session.close();
				modifiedEntities.clear();
			}
		}
	}

	@Override
	protected void OtherSave4jvm(PlayerLog entity) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected Collection<PlayerLog> dbFindAll() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void dbSave(PlayerLog entity) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void otherDelete4Jvm(PlayerLog entity) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void dbDelete(Integer id) {
		// TODO Auto-generated method stub
		
	}

	public List<Integer> getPlayerCreateRoomLog(long userId, int operationType, int clubId, String time){
		try(SqlSession session = SessionUtil.getSession()){
			PlayerLogMapper mapper = session.getMapper(PlayerLogMapper.class);
			return mapper.selectCreateRoom(userId, operationType, clubId, time);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
